package com.central.apps.handler.purchase;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.util.ToolUtil;
import com.central.common.web.PageResult;
import com.central.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.print.DocFlavor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static java.lang.Math.abs;
import static java.lang.Math.incrementExact;

/**
 * 处理采购订单业务逻辑
 *
 * @author lidachao
 * @date 2022/8/11
 */
@Component
@Slf4j
public class PurchaseOrderHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        if ("gq_po".equals(objName)) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where poid=" + id);
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    String id1 = MapUtils.getString(map, "id");
                    // 更新采购计划行标记001
                    handlerService.updateBySql("update gq_ppline set converttopo = 0 where id in (select pplid from gq_poline where poid = " + id + ")");
                }
            }

            // 更新采购计划汇总行标记
            handlerService.updateBySql("update gq_ppsummaryline set converttopo = 0 where id in (select ppslid from gq_posline where poid = " + id + ")");
        } else if ("gq_posline".equals(objName)){
            // 查询采购订单汇总行信息
            List<Map<String, Object>> poslList = handlerService.findBySql("select * from gq_posline t where id = " + id);
            Map<String, Object> poslMap = poslList.get(0);
            Integer ppslid = MapUtils.getInteger(poslMap, "ppslid");
            Integer ppid = MapUtils.getInteger(poslMap, "ppid");
            Integer poid = MapUtils.getInteger(poslMap, "poid");

            // 更新采购计划汇总行标记
            handlerService.updateBySql("update gq_ppsummaryline set converttopo = 0 where id = " + ppslid);
            // 删除采购订单明细行
            handlerService.findBySql("delete from gq_poline where poid = " + poid + " and ppid = " + ppid + " and ppslid = " + ppslid);
            // 更新采购计划行标记
            handlerService.updateBySql("update gq_ppline set converttopo = 0 where ppid = " + ppid + " and ppslid = " + ppslid);
            //删除订单会总行，减少计划会总行订单数量
//            Float number = MapUtils.getFloat(poslMap, "number");
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_ppsummaryline where id=" + ppslid);
//            if (CollectionUtils.isNotEmpty(bySql)) {
//                Map<String, Object> map = bySql.get(0);
//                Float number1 = MapUtils.getFloat(map, "number");
//                number1=number1-number;
//                handlerService.updateBySql("update gq_ppsummaryline set number ="+number1+" where id="+ppslid);
//            }
        }
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if("submit".equals(flowNode.getId())) {
            List<Map<String, Object>> list = handlerService.findBySql("select id,ponum from gq_posline where poid = " + id);
            if (CollectionUtils.isEmpty(list)) {
                return "请选择采购计划添加采购订单汇总行信息！";

            }else if (CollectionUtils.isNotEmpty(list)){
                for (int i=0;i<list.size();i++){
                    Map<String, Object> map = list.get(i);
                    String id1 = MapUtils.getString(map, "id");
                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where id='" + id1 + "'");//查询订单会总行的计划会总行id
                    Map<String, Object> map1 = bySql.get(0);
                    String ppslid = MapUtils.getString(map1, "ppslid");
                    Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//会总行订单数量
//                    List<Map<String, Object>> bySql1 = handle rService.findBySql("select * from gq_posline where ppslid ='" + ppslid + "'");//根据计划会总行id查询所有订单会总行的数量
//                    float orderqtys=0;
//                    if (CollectionUtils.isNotEmpty(bySql1)){
//                        for (int j=0;j<bySql1.size();j++){
//                            Map<String, Object> map2 = bySql1.get(j);
//                            Float orderqty = MapUtils.getFloat(map2, "orderqty");
//                            orderqtys =orderqtys+orderqty;
//                        }
//                        handlerService.updateBySql("update gq_posline set innum="+orderqtys+" where id='" + id1 + "'");
//                    }
                    String ponum = MapUtils.getString(map, "ponum");
                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_poline where ponum='" + ponum + "' and poslid='" + id1 + "'");
                    if (CollectionUtils.isNotEmpty(bySql2)){
                        float orderqty0=0;
                        for (int j=0;j<bySql2.size();j++){
                            Map<String, Object> map2 = bySql2.get(j);
                            Float orderqty = MapUtils.getFloat(map2, "orderqty");
                            orderqty0=orderqty0+orderqty;
                        }
                        if (orderqty1.compareTo(orderqty0)==0){

                        }else {
                            return "采购申请行采购数量之和不等于采购订单行数量，请查看！";
                        }
                    }
                }
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select ponum from gq_po where id=" + id);
                String ponum2 = MapUtils.getString(bySql1.get(0), "ponum");
                List<Map<String, Object>> bySql = handlerService.findBySql("select totalcost,demount,id from gq_posline where ponum='"+ponum2+"' and poid=" + id);
                if (CollectionUtils.isNotEmpty(bySql)){

                    for (int i=0;i<bySql.size();i++){
                        Map<String, Object> map = bySql.get(i);
                        String totalcost = MapUtils.getString(map, "totalcost");
                        String demount = MapUtils.getString(map, "demount");
                        BigDecimal bigDecimal = new BigDecimal(totalcost);
                        BigDecimal bigDecimal1 = new BigDecimal(demount);
                        BigDecimal bigDecimal2 = new BigDecimal("0");
                        BigDecimal bigDecimal3 = new BigDecimal("0");
                        BigDecimal bigDecimal4 = new BigDecimal("100");
                        BigDecimal bigDecimal5 = new BigDecimal("0.1");
                        bigDecimal2=bigDecimal.subtract(bigDecimal1);
                        bigDecimal3=bigDecimal2.divide(bigDecimal4,2,BigDecimal.ROUND_HALF_UP);
                        if (bigDecimal3.compareTo(bigDecimal5)>0){
                            return "订单金额超过预算金额10%,请修改订单或关闭订单！";
                        }
//                    Integer id1 = MapUtils.getInteger(map, "id");
//                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_poline where ponum='" + ponum + "' poid =" + id1);
//                    if (CollectionUtils.isNotEmpty(bySql2)){
//                        for (int j=0;j<bySql2.size();j++){
//                            Map<String, Object> map1 = bySql2.get(j);
//                            Float orderqty = MapUtils.getFloat(map1, "orderqty");
//                        }
//                    }
                    }
                }
                //采购订单占用采购计划
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
                if (CollectionUtils.isNotEmpty(bySql2)){
                    for (int i=0;i<bySql2.size();i++){
                        Map<String, Object> map = bySql2.get(i);
                        String ppslid = MapUtils.getString(map, "ppslid");//采购计划明细行id
                        String poid = MapUtils.getString(map, "poid");//采购订单主id
                        String id1 = MapUtils.getString(map, "id");//采购订单会总行id
                        Float orderqty = MapUtils.getFloat(map, "orderqty");//采购订单数量
                        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_posline t left join gq_po a on t.poid=a.id where t.ppslid='" + ppslid + "' and a.status!='新建' and  a.status!='已作废' and a.status!='已批准'");
                        float quantity2 = 0;
                        if (CollectionUtils.isNotEmpty(bySql5)){
                            for (int j=0;j<bySql5.size();j++){
                                Map<String, Object> map1 = bySql5.get(j);
                                Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//采购订单数量
                                quantity2=quantity2+orderqty1;//审批中的采购订单总数量
                            }
                            List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_ppsummaryline where id='" + ppslid + "'");
                            if (CollectionUtils.isNotEmpty(bySql6)){
                                Float orderqty1 = MapUtils.getFloat(bySql6.get(0), "orderqty");//采购计划数量
                                Float ordernot = MapUtils.getFloat(bySql6.get(0), "ordernot");//审批完成订单数量
                                if (quantity2>=orderqty1){
                                    int y=i+1;
                                    return "该订单第"+y+"行物料，订单数量已超过计划数量！";
                                }
                            }
                        }
                    }
                }
                List<Map<String, Object>> poList = handlerService.findBySql("select * from gq_po where id = " + id);
                Map<String, Object> poMap = poList.get(0);
                String ponum = MapUtils.getString(poMap, "ponum");
                //修改采购计划会总行订单数量
                List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and  poid=" + id);
                if (CollectionUtils.isNotEmpty(bySql5)){
                    for (int i=0;i<bySql5.size();i++){
                        Map<String, Object> map = bySql5.get(i);
                        Integer id1 = MapUtils.getInteger(map, "id");
                        Float orderqty = MapUtils.getFloat(map, "orderqty");
                        Integer ppslid = MapUtils.getInteger(map, "ppslid");
                        List<Map<String, Object>> bySql6 = handlerService.findBySql("select number,ordernot,orderqty from gq_ppsummaryline where id=" + ppslid);
                        if (CollectionUtils.isNotEmpty(bySql6)){
                            Map<String, Object> map1 = bySql6.get(0);
                            Float number1 = MapUtils.getFloat(map1, "number");//采购计划会总行订单数量
                            Float ordernot = Float.valueOf(0);
                            if(ToolUtil.isNotEmpty(map1.get("ordernot"))){
                                ordernot =  MapUtils.getFloat(map1, "ordernot");//汇总行对主表订单状态进行控制的订单数量
                            }
                            Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//采购计划数量

                            number1=number1-orderqty;
                            ordernot=ordernot+orderqty;//统计订单数量
                            handlerService.updateBySql("update gq_ppsummaryline set number="+number1+",ordernot="+ordernot+" where id="+ppslid);
                            //生成订单，未提交状态下无法再次生成订单，已提交但订单数量小于计划数量时，可以再次生成
                            if (ordernot<orderqty1){
                                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 0 where id = " + ppslid);
                                handlerService.updateBySql("update gq_ppline set converttopo = 0 where ppid = '"+id+"'");
                            }else {
                                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 2 where id = " + ppslid);
                                handlerService.updateBySql("update gq_ppline set converttopo = 2 where ppid = '"+id+"'");
                            }
                        }

                    }
                }
                //测试采购订单是否全部下订单
                List<Map<String, Object>> bySql3 = handlerService.findBySql("select ppnum from gq_po where ponum='" + ponum + "'");
                if (CollectionUtils.isNotEmpty(bySql3)){
                    String ppnum = MapUtils.getString(bySql3.get(0), "ppnum");//获取采购计划编号
                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_ppsummaryline where ppnum='" + ppnum + "'");
                    if (CollectionUtils.isNotEmpty(bySql4)){
                        int sumnum =0;
                        for (int i=0;i<bySql4.size();i++){
                            Map<String, Object> map = bySql4.get(i);
                            String ppslid = MapUtils.getString(map, "id");
                            List<Map<String, Object>> bySql6 = handlerService.findBySql("select orderqty,ordernot from gq_ppsummaryline where id=" + ppslid);
                            if (CollectionUtils.isNotEmpty(bySql6)){
                                    float numer=0;
                                    Map<String, Object> map1 = bySql6.get(0);
                                    Float orderqty = MapUtils.getFloat(map1, "orderqty");//计划数量
                                    Float ordernot = MapUtils.getFloat(map1, "ordernot");//订单统计数量
                                    numer=ordernot-orderqty;//判断订单统计数量是否大于计划数量
                                    if (numer>=0){
                                        sumnum++;
                                    }

                            }
                        }
                        if (sumnum<bySql1.size()){
                            String ordernot ="部分订单";
                            handlerService.updateBySql("update gq_purchaseplan set ordernot='"+ordernot+"' where ppnum='"+ppnum+"'");
                        }else {
                            String ordernot ="全部订单";
                            handlerService.updateBySql("update gq_purchaseplan set ordernot='"+ordernot+"' where ppnum='"+ppnum+"'");
                        }
                    }
                }
            }


//            //判定采购订单数量是否大于计划数量
//            List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
//            if (CollectionUtils.isNotEmpty(bySql3)){
//                for (int i=0;i<bySql3.size();i++){
//                    Map<String, Object> map = bySql3.get(i);
//                    Float orderqty = MapUtils.getFloat(map, "orderqty");//采购订单数量
//                    String ppslid = MapUtils.getString(map, "ppslid");//采购计划会总行id
//                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_posline t left join gq_po a on t.poid=a.id where t.ppslid='" + ppslid + "' and  a.status!='已作废'");
//                    float quantity2 = 0;
//                    if (CollectionUtils.isNotEmpty(bySql4)){
//                        for (int j=0;j<bySql.size();j++){
//                            Map<String, Object> map1 = bySql4.get(j);
//                            Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//采购订单数量
//                            quantity2=quantity2+orderqty1;//审批中的采购订单总数量
//                        }
//                        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_ppsummaryline where id='" + ppslid + "'");
//                        if (CollectionUtils.isNotEmpty(bySql5)){
//                            Float orderqty1 = MapUtils.getFloat(bySql5.get(0), "orderqty");//采购计划数量
//                            Float ordernot = MapUtils.getFloat(bySql5.get(0), "ordernot");//审批完成订单数量
//                            if (quantity2<orderqty1){
//                                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 1 where id = " + ppslid);
//                            }
//                        }
//                    }
//                }
//            }
        }
        return null;
    }

    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        List<Map<String, Object>> bySql2 = handlerService.findBySql(" select ppnum,ponum from gq_po where id='" + id + "'");
        if (CollectionUtils.isNotEmpty(bySql2)){
            String ppnum = MapUtils.getString(bySql2.get(0), "ppnum");
            String ponum = MapUtils.getString(bySql2.get(0), "ponum");
            handlerService.updateBySql("update gq_ppsummaryline set converttopo = 1 where ppnum = '" + ppnum+"'");
            handlerService.updateBySql("update gq_ppline set converttopo = 1 where ppnum = '"+ppnum+"'");
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                int num=0;
                for (int i=0;i<bySql.size();i++){
                    String ppslid = MapUtils.getString(bySql.get(i), "ppslid");
                    Float orderqty = MapUtils.getFloat(bySql.get(i), "orderqty");
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select number,ordernot from gq_ppsummaryline where id='" + ppslid + "'");
                    if (CollectionUtils.isNotEmpty(bySql1)){
                        Float number = MapUtils.getFloat(bySql1.get(0), "number");
                        Float ordernot = MapUtils.getFloat(bySql1.get(0), "ordernot");
                        number=number+orderqty;
                        ordernot=ordernot-orderqty;
                        handlerService.updateBySql("update gq_ppsummaryline set number="+number+",ordernot="+ordernot+" where id='"+ppslid+"'");
                        //判断是否为部分订单
                        if (ordernot>0){
                            num=num+1;
                        }
                    }
                }
                if (num >0){
                //更改采购计划订单状态
                    String ordernot ="部分订单";
                     handlerService.updateBySql("update gq_purchaseplan set ordernot='"+ordernot+"' where ppnum='"+ppnum+"'");
                }else {
                    String ordernot ="未下订单";
                    handlerService.updateBySql("update gq_purchaseplan set ordernot='"+ordernot+"' where ppnum='"+ppnum+"'");
                }
            }
        }
        List<Map<String, Object>> poList = handlerService.findBySql("select * from gq_po where id = " + id);
        Map<String, Object> poMap = poList.get(0);
        String ponum = MapUtils.getString(poMap, "ponum");
        //修改采购计划会总行订单数量
        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and  poid=" + id);
        if (CollectionUtils.isNotEmpty(bySql5)){
            for (int i=0;i<bySql5.size();i++){
                Map<String, Object> map = bySql5.get(i);
                Integer id1 = MapUtils.getInteger(map, "id");
                Float orderqty = MapUtils.getFloat(map, "orderqty");
                Integer ppslid = MapUtils.getInteger(map, "ppslid");
                List<Map<String, Object>> bySql6 = handlerService.findBySql("select number,ordernot,orderqty from gq_ppsummaryline where id=" + ppslid);
                if (CollectionUtils.isNotEmpty(bySql6)){
                    Map<String, Object> map1 = bySql6.get(0);
                    Float number1 = MapUtils.getFloat(map1, "number");//采购计划会总行订单数量
                    Float ordernot = Float.valueOf(0);
                    if(ToolUtil.isNotEmpty(map1.get("ordernot"))){
                        ordernot =  MapUtils.getFloat(map1, "ordernot");//汇总行对主表订单状态进行控制的订单数量
                    }
                    Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//采购计划数量

                    number1=number1+orderqty;
                    ordernot=ordernot-orderqty;//统计订单数量
                    handlerService.updateBySql("update gq_ppsummaryline set number="+number1+",ordernot="+ordernot+" where id="+ppslid);
                    handlerService.updateBySql("update gq_posline set innum=0 where id='" + id1 + "'");
                    //生成订单，未提交状态下无法再次生成订单，已提交但订单数量小于计划数量时，可以再次生成

                        handlerService.updateBySql("update gq_ppsummaryline set converttopo = 1 where id = " + ppslid);
                        handlerService.updateBySql("update gq_ppline set converttopo = 1 where ppid = '"+id+"'");

                }

            }
        }

    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if ("complete".equals(flowNode.getId()) && op.isFlag()){
            // 查询采购订单信息
            List<Map<String, Object>> poList = handlerService.findBySql("select * from gq_po where id = " + id);
            Map<String, Object> poMap = poList.get(0);
            Map<String, Object> paMap = new HashMap<String, Object>(5);

            // 转换采购订单为采购台账数据
            paMap.put("poid", poMap.get("id"));
            paMap.put("orgcode", poMap.get("orgcode"));// 总公司
            paMap.put("sitecode", poMap.get("sitecode"));// 分公司
            paMap.put("deptcode", poMap.get("deptcode"));// 部门
            paMap.put("suppliernum",poMap.get("suppliernum"));//供应商编码
            paMap.put("suppliername",poMap.get("suppliername"));//供应商名称

            handlerService.insert("gq_purchaseaccount", paMap);

            String suppliername = MapUtils.getString(poMap, "suppliername");//供应商名称
            String billtoattn = MapUtils.getString(poMap, "billtoattn");//接收人
            handlerService.updateBySql("update gq_posline set suppliername='"+suppliername+"',billtoattn='"+billtoattn+"' where poid='"+id+"'");
            //统计采购订单综总金额
            BigDecimal bigDecimal1 = new BigDecimal("0");
            List<Map<String, Object>> bySql = handlerService.findBySql("select linecost from gq_poline where poid='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    String linecost = MapUtils.getString(map, "linecost");
                    BigDecimal bigDecimal = new BigDecimal(linecost);
                    bigDecimal1=bigDecimal1.add(bigDecimal);
                }
                handlerService.updateBySql("update gq_po set toderount="+bigDecimal1+" where id='"+id+"'");
            }
//            String ponum = MapUtils.getString(poMap, "ponum");
//            //修改采购计划会总行订单数量
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and  poid=" + id);
//            if (CollectionUtils.isNotEmpty(bySql)){
//                for (int i=0;i<bySql.size();i++){
//                    Map<String, Object> map = bySql.get(i);
//                    Integer id1 = MapUtils.getInteger(map, "id");
//                    Float orderqty = MapUtils.getFloat(map, "orderqty");
//                    Integer ppslid = MapUtils.getInteger(map, "ppslid");
//                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select number from gq_ppsummaryline where id=" + ppslid);
//                    if (CollectionUtils.isNotEmpty(bySql1)){
//                        Map<String, Object> map1 = bySql1.get(0);
//                        Float number1 = MapUtils.getFloat(map1, "number");
//                        number1=number1-orderqty;
//                        handlerService.updateBySql("update gq_ppsummaryline set number="+number1+" where id="+ppslid);
//
//                    }
////                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_ppsummaryline where id=" + ppslid);
////                    if (CollectionUtils.isNotEmpty(bySql1)){
////                        for (int y=0;y<bySql1.size();y++){
////                            Map<String, Object> map1 = bySql1.get(y);
////                            Float number1 = MapUtils.getFloat(map1, "number");
////                            Float orderqty = MapUtils.getFloat(map1, "orderqty");
////                        }
////                    }
//
//                }
//            }
        }
    }

    @Override
    public String beforeCloseFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        System.out.println("======流程关闭前===========流程关闭前，所走流程逻辑========");
        System.out.println("app==="+app);
        System.out.println("id ===="+id);
        System.out.println("flowNode===="+flowNode.toString());
        System.out.println("op======="+op.toString());
        return null;
    }

    @Override
    public void afterCloseFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        //测试流程关闭后，编写业务逻辑是否生效
        System.out.println("=================流程关闭后，所走流程逻辑========");
        System.out.println("app==="+app);
        System.out.println("id ===="+id);
        System.out.println("flowNode===="+flowNode.toString());
        System.out.println("op======="+op.toString());
//        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where poid='" + id + "'");
//        if (CollectionUtils.isNotEmpty(bySql)){
//            for (int i=0;i<bySql.size();i++){
//                Map<String, Object> map = bySql.get(i);
//                String ppid = MapUtils.getString(map, "ppid");
//                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 0 where ppid = " + ppid);
//            }
//        }
//        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_poline where poid='" + id + "'");
//        if (CollectionUtils.isNotEmpty(bySql1)){
//            for (int i=0;i<bySql1.size();i++){
//                Map<String, Object> map = bySql1.get(i);
//                String ppid = MapUtils.getString(map, "ppid");
//                handlerService.updateBySql("update gq_ppline set converttopo = 0 where ppid = " + ppid);
//
//            }
//        }
        List<Map<String, Object>> poList = handlerService.findBySql("select * from gq_po where id = " + id);
        Map<String, Object> poMap = poList.get(0);
        String ponum = MapUtils.getString(poMap, "ponum");
        //修改采购计划会总行订单数量
        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and  poid=" + id);
        if (CollectionUtils.isNotEmpty(bySql5)){
            for (int i=0;i<bySql5.size();i++){
                Map<String, Object> map = bySql5.get(i);
                Integer id1 = MapUtils.getInteger(map, "id");
                Float orderqty = MapUtils.getFloat(map, "orderqty");
                Integer ppslid = MapUtils.getInteger(map, "ppslid");
                List<Map<String, Object>> bySql6 = handlerService.findBySql("select number,ordernot,orderqty from gq_ppsummaryline where id=" + ppslid);
                if (CollectionUtils.isNotEmpty(bySql6)){
                    Map<String, Object> map1 = bySql6.get(0);
                    Float number1 = MapUtils.getFloat(map1, "number");//采购计划会总行订单数量
                    Float ordernot = Float.valueOf(0);
                    if(ToolUtil.isNotEmpty(map1.get("ordernot"))){
                        ordernot =  MapUtils.getFloat(map1, "ordernot");//汇总行对主表订单状态进行控制的订单数量
                    }
                    Float orderqty1 = MapUtils.getFloat(map1, "orderqty");//采购计划数量

                    number1=number1+orderqty;
                    ordernot=ordernot-orderqty;//统计订单数量
                    handlerService.updateBySql("update gq_ppsummaryline set number="+number1+",ordernot="+ordernot+" where id="+ppslid);
                    handlerService.updateBySql("update gq_posline set innum=0 where id='" + id1 + "'");

                    //生成订单，未提交状态下无法再次生成订单，已提交但订单数量小于计划数量时，可以再次生成

                    handlerService.updateBySql("update gq_ppsummaryline set converttopo = 0 where id = " + ppslid);
                    handlerService.updateBySql("update gq_ppline set converttopo = 0 where ppid = '"+id+"'");

                }

            }
        }
    }

//修改采购订单会总行订单数量
//    @Override
//    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("gq_po".equals(objName)){
//
//                Integer id = MapUtils.getInteger(data, "id");
//                String ponum = MapUtils.getString(data, "ponum");
//                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and poid =" + id);
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        Float orderqty = MapUtils.getFloat(map, "orderqty");
//                        Integer id1 = MapUtils.getInteger(map, "id");
//                        handlerService.updateBySql("update gq_posline set number ="+orderqty+" where id="+id1);
//
//                    }
//            }
//        }
//        super.beforSave(app, objName, data, isUpdate);
//    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_posline".equals(objName)) {

            //根据订单汇总行中的下单日期、到货周期，计算计划到货日期（计划到货日期=下单日期+到货周期）
            findArrivalDate(data);

            if (isUpdate==false){
                Integer poid = MapUtils.getInteger(data, "poid");
                String ponum = MapUtils.getString(data, "ponum");
                Integer ppid = MapUtils.getInteger(data, "ppid");
                Integer ppslid = MapUtils.getInteger(data, "ppslid");
//            String createuser = MapUtils.getString(data, "createuser");
//            String deptcode = MapUtils.getString(data, "deptcode");
                //Integer id2 = MapUtils.getInteger(data, "id");
                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 1 where id = " + ppslid);
                //添加物料主数据id
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and poid=" + poid + " and ppslid = " + ppslid);
                if (CollectionUtils.isNotEmpty(bySql1)){
                    for (int j=0;j<bySql1.size();j++){
                        Map<String, Object> map1 = bySql1.get(j);
                        Integer id1 = MapUtils.getInteger(map1, "id");
                        String itemnum = MapUtils.getString(map1, "itemnum");
                        String orderqty1 = MapUtils.getString(map1, "orderqty");
                        BigDecimal bigDecimal1 = new BigDecimal(orderqty1);
                        String unitcost = MapUtils.getString(map1, "unitcost");
                        BigDecimal bigDecimal2 = new BigDecimal(unitcost);
                        String totalcost = MapUtils.getString(map1, "totalcost");
                        BigDecimal bigDecimal6 = new BigDecimal(totalcost);
                        List<Map<String, Object>> bySql = handlerService.findBySql("select id,taxrate  from gq_item where itemnum='" + itemnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql)){
                            Map<String, Object> map = bySql.get(0);
                            Integer id = MapUtils.getInteger(map, "id");
                            Float taxrate = MapUtils.getFloat(map, "taxrate");
                            String taxrate1 = String.valueOf(taxrate);
                            BigDecimal bigDecimal = new BigDecimal(taxrate1);
                            BigDecimal bigDecimal3 = new BigDecimal("1");
                            BigDecimal bigDecimal4 = new BigDecimal("0");
                            //:unitcost*:orderqty/(1+:taxrate)无税金额
                            bigDecimal4=bigDecimal6.divide(bigDecimal.add(bigDecimal3),2,BigDecimal.ROUND_HALF_UP);
                            //double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                            //:unitcost*:orderqty-:unitcost*:orderqty/(1+:taxrate)//税额
                            BigDecimal bigDecimal5 = new BigDecimal("0");
                            //ma.subtract(mb)
                            bigDecimal5=bigDecimal6.subtract(bigDecimal4);
                            handlerService.updateBySql("update gq_posline set itemid="+id+",taxrate='"+taxrate+"',amexclutax='"+bigDecimal4+"',taxamount='"+bigDecimal5+"' where id="+id1);
                        }
//                        Integer ppid = MapUtils.getInteger(map1, "ppid");
                        String createuser = MapUtils.getString(map1, "createuser");
                        String deptcode = MapUtils.getString(map1, "deptcode");
                        /*
                         * 复制采购计划明细行
                         */
                        // 查询采购计划明细行
                        //超哥写的
                        //List<Map<String, Object>> pplList = handlerService.findBySql("select * from gq_ppline t where not exists (select 1 from gq_poline a where a.pplid = t.id and ppid = " + ppid + " and ppslid = " + ppslid + ") and ppid = " + ppid + " and ppslid = " + ppslid);
                        List<Map<String, Object>> pplList = handlerService.findBySql("SELECT * from gq_ppline where ppid = " + ppid + "  and ppslid = " + ppslid+"");
                        //

                        if (CollectionUtils.isNotEmpty(pplList)) {
                            List<Map<String, Object>> polineDatas = new ArrayList<>();
                            for (Map<String, Object> pplMap : pplList) {
                                int pplid = (int) pplMap.get("id");
                                float orderqty = (float) pplMap.get("orderqty");
                                Map<String, Object> polineMap = new HashMap<>();

                                // 组织采购订单明细数据
                                polineMap.put("poslid",id1);
                                polineMap.put("poid",poid);
                                polineMap.put("ponum", ponum);
                                polineMap.put("ppid", pplMap.get("ppid"));
                                polineMap.put("ppslid", pplMap.get("ppslid"));
                                polineMap.put("pplid", pplMap.get("id"));
                                polineMap.put("proid", pplMap.get("proid"));
                                polineMap.put("taskid", pplMap.get("taskid"));
                                polineMap.put("prid", pplMap.get("prid"));
                                polineMap.put("prlid", pplMap.get("prlid"));
                                polineMap.put("pplinenum", pplMap.get("pplinenum"));
                                polineMap.put("ppnum", pplMap.get("ppnum"));
                                polineMap.put("prnum", pplMap.get("prnum"));

                                polineMap.put("requestedby", createuser);
                                polineMap.put("reqdeptcode", deptcode);

                                polineMap.put("itemtype", pplMap.get("itemtype"));
                                polineMap.put("itemnum", pplMap.get("itemnum"));
                                polineMap.put("itemdesc", pplMap.get("itemdesc"));
                                polineMap.put("spemodel", pplMap.get("spemodel"));
                                polineMap.put("qualitygrade", pplMap.get("qualitygrade"));
                                polineMap.put("specifications",pplMap.get("specifications"));
                                polineMap.put("manufacturer", pplMap.get("manufacturer"));
                                polineMap.put("packform", pplMap.get("packform"));
                                polineMap.put("maintechtors", pplMap.get("maintechtors"));
                                polineMap.put("model", pplMap.get("model"));
                                polineMap.put("orderqty", orderqty);
                                polineMap.put("arrquantity",orderqty);
                                polineMap.put("uninspectqty", orderqty);
                                polineMap.put("inspectqty", 0);
                                polineMap.put("unrejectedqty", orderqty);
                                polineMap.put("rejectedqty", 0);
                                polineMap.put("unreceivedqty", orderqty);
                                polineMap.put("receivedqty", 0);
                                polineMap.put("receivedlinecost", 0);
                                polineMap.put("receivedunitcost", 0);
                                polineMap.put("receivedtotalcost", 0);

                                polineMap.put("orderunit", pplMap.get("orderunit"));
                                polineMap.put("unitcost", bigDecimal2);
                                polineMap.put("taxcode", pplMap.get("taxcode"));
                                polineMap.put("taxrate", pplMap.get("taxrate"));
                                BigDecimal bigDecimal = new BigDecimal(orderqty);
                                BigDecimal bigDecimal3 = new BigDecimal(0);
                                bigDecimal3=bigDecimal2.multiply(bigDecimal);
                                polineMap.put("linecost", bigDecimal3);


                                polineMap.put("whfournew", pplMap.get("whfournew"));
                                polineMap.put("whethdangerous", pplMap.get("whethdangerous"));
                                polineMap.put("advisupplier", pplMap.get("advisupplier"));
                                polineMap.put("contacts", pplMap.get("contacts"));
                                polineMap.put("phone", pplMap.get("phone"));
                                polineMap.put("rearecommendation", pplMap.get("rearecommendation"));
                                polineMap.put("reqdeliverydate", pplMap.get("reqdeliverydate"));
                                polineMap.put("acceptments", pplMap.get("acceptments"));
                                polineMap.put("wheprocuremen", pplMap.get("wheprocuremen"));
                                polineMap.put("commerceorder", pplMap.get("commerceorder"));
                                polineMap.put("reasonpur", pplMap.get("reasonpur"));
                                polineMap.put("type",pplMap.get("type"));
                                polineMap.put("production", pplMap.get("production"));
                                polineMap.put("requiredtime", pplMap.get("requiredtime"));
                                polineMap.put("unifiedno", pplMap.get("unifiedno"));
                                polineMap.put("researchmode", pplMap.get("researchmode"));
                                polineMap.put("productmode", pplMap.get("productmode"));
                                polineMap.put("purchasemethod", pplMap.get("purchasemethod"));
                                polineMap.put("invitationmethod", pplMap.get("invitationmethod"));
                                polineMap.put("purchasenote", pplMap.get("purchasenote"));
                                polineMap.put("occupnot", pplMap.get("occupnot"));
                                polineMap.put("applyby", pplMap.get("applyby"));
                                polineMap.put("componentsparts", pplMap.get("componentsparts"));
                                polineMap.put("isdpaanalysis", pplMap.get("isdpaanalysis"));
                                polineMap.put("specialrequirements", pplMap.get("specialrequirements"));
                                polineMap.put("isspeciallymade", pplMap.get("isspeciallymade"));
                                polineMap.put("isfactoryacceptance", pplMap.get("isfactoryacceptance"));
                                polineMap.put("isinspection", pplMap.get("isinspection"));
                                polineMap.put("inspectionreq", pplMap.get("inspectionreq"));
                                polineMap.put("subjectno", pplMap.get("subjectno"));//课题号
                                polineMap.put("typeline",pplMap.get("typeline"));
                                polineDatas.add(polineMap);


                                // 更新采购计划明细信息
                                handlerService.updateBySql("update gq_ppline set converttopo = 1 where id = " + pplid);
                            }
                            // 批量插入采购订单明细
                            handlerService.batchInsert("poApp", "gq_poline", polineDatas);
                        }
                    }
                }



                // 查询采购订单采购到货日期
                List<Map<String, Object>> poList = handlerService.findBySql("select requireddate from gq_po where id = " + poid);
                String requiredDate ="";
                if(CollectionUtils.isNotEmpty(poList)){
                    requiredDate= MapUtils.getString(poList.get(0), "requireddate");
                }



                // 更新采购订单行采购到货日期
                handlerService.updateBySql("update gq_posline set reqdeliverydate = '" + requiredDate + "' where poid = " + poid);

                // 查询采购申请子表信息
                List<Map<String, Object>> poslList = handlerService.findBySql("select totalcost from gq_posline t where t.poid = " + poid);
                if (CollectionUtils.isNotEmpty(poslList)) {
                    // 组织插入数据
//                float poTotalcost = 0f;
                    BigDecimal poTotalcost = new BigDecimal("0");
                    for (Map<String, Object> poslMap : poslList) {
                        String linecost = MapUtils.getString(poslMap, "totalcost");
                        BigDecimal bigDecimal1 = new BigDecimal(linecost);
                        poTotalcost = poTotalcost.add(bigDecimal1);
//                    float totalcost = (float) poslMap.get("totalcost");
//
//                    poTotalcost = poTotalcost + totalcost;
                    }

                    // 修改采购申请信息
                    handlerService.updateBySql("update gq_po set totalcost = " + poTotalcost + " where id = " + poid);
                    // 修改采购申请是否存在子表数据
                    handlerService.updateBySql("update gq_po set haschild = 1 where haschild = 0 and id = " + poid);
                }
            }else if(isUpdate==true){
                Integer poid = MapUtils.getInteger(data, "poid");
                String ponum = MapUtils.getString(data, "ponum");
                Integer ppid = MapUtils.getInteger(data, "ppid");
                Integer ppslid = MapUtils.getInteger(data, "ppslid");
                List<Map<String, Object>> pplList = handlerService.findBySql("SELECT * from gq_posline where poid = " + poid + " and ponum = '" + ponum+"'");
                if (CollectionUtils.isNotEmpty(pplList)){
                    for (int i=0;i<pplList.size();i++){
                        Map<String, Object> map = pplList.get(i);
                        Float orderqty = MapUtils.getFloat(map, "orderqty");
                        Integer id = MapUtils.getInteger(map, "id");
                        handlerService.updateBySql("update gq_posline set unreceivedqty ="+orderqty+" where id="+id);
                    }
                }
            }
        } else if ("gq_po".equals(objName)) {
            Integer poid = MapUtils.getInteger(data, "id");

            // 修改采购申请是否存在子表数据
            handlerService.updateBySql("update gq_po set haschild = 0 where haschild is null and id = " + poid);
            // 修改采购订单待付金额、已付金额
            handlerService.updateBySql("update gq_po set unpaidamt = totalprice where id = " + poid);

        }
    }

    /*
        根据订单汇总行中的下单日期、到货周期，计算计划到货日期（计划到货日期=下单日期+到货周期）
     */
    private void findArrivalDate(Map<String, Object> data) {
        String id = MapUtils.getString(data, "id");//采购订单汇总行id
        String commertime = MapUtils.getString(data, "commertime");//下单日期
        Integer deliverycycle = MapUtils.getInteger(data, "deliverycycle");//到货周期
        if(StringUtils.isNotBlank(commertime)&&deliverycycle!=null){
            Date date = DateUtils.strToDate(commertime, "yyyy-MM-dd");
            Date expectdeldate = DateUtils.addDateByDay(date, deliverycycle);
            String expectdeldateStr = DateUtils.dateToStr(expectdeldate, "yyyy-MM-dd");
            handlerService.findBySql("update gq_posline set expectdeldate = '" +expectdeldateStr +"' where id ='" + id +"'");
        }
    }

//    @Override
//    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//
//        super.beforSave(app, objName, data, isUpdate);
//    }

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("poApp".equals(app)){


        if ("PurchaseOrder".equals(type)){
            List<Map<String, Object>> bySql = handlerService.findBySql("SELECT a.taxrate,b.* from gq_item a left join gq_ppsummaryline b on a.itemnum=b.itemnum ");
            if (CollectionUtils.isNotEmpty(bySql)) {
                int page = 1;
                int limit = 10;
                if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                    page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                    limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                }

                List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
            }
            List<Map<String, Object>> result = new ArrayList<>();
            return PageResult.<Map<String, Object>>builder().data(result).code(0).count(0L).build();
        }
        }
        return super.operate(app, type, params);
    }
}
